﻿
// First: Create config
ko.validation.configure({
	registerExtenders: true,
	messagesOnModified: true,
	insertMessages: true,
	parseInputAttributes: true,
	messageTemplate: null,
	decorateElement: true,
	errorClass: "error",
	errorMessageClass: "error-desc"
});
var mustEqual = function (val, other) {
	return val == other();
};

// Second: Create new model to apply to view
var viewModel = new function () {
    // About you
    this.Fullname = ko.observable(data.UserInfo.Fullname).extend({ maxLength: 50 }).extend({ required: { message: "Fullname is required"} }).extend({ pattern: {
        message: 'Invalid Characters',
        params: '^[a-zA-Z0-9 ]\{1,50\}$'
    }
    });
    this.FirstName = ko.observable(data.UserInfo.FirstName).extend({ maxLength: 50 }).extend({ required: { message: "First Name is required"} }).extend({ pattern: {
        message: 'Invalid Characters',
        params: '^[a-zA-Z0-9 ]\{1,50\}$'
    }
    });
    this.LastName = ko.observable(data.UserInfo.LastName).extend({ maxLength: 50 }).extend({ required: { message: "Last Name is required"} }).extend({ pattern: {
        message: 'Invalid Characters',
        params: '^[a-zA-Z0-9 ]\{1,50\}$'
    }
    });
    this.Email = ko.observable(data.UserInfo.Email).extend({ required: { message: 'Enter a valid email'} }).extend({ email: { message: 'Enter a valid email'} });
    this.Password = ko.observable(data.UserInfo.Password);
    this.ConfirmPassword = ko.observable(data.UserInfo.Password);

    this.Phone = ko.observable(data.UserInfo.Phone);
    this.PhoneExt = ko.observable(data.UserInfo.PhoneExt);
    this.Mobile = ko.observable(data.UserInfo.Mobile);
    this.Fax = ko.observable(data.UserInfo.Fax);
    this.Address = ko.observable(data.UserInfo.Address);
    this.City = ko.observable(data.UserInfo.City);
    this.Zipcode = ko.observable(data.UserInfo.ZipCode);

    this.State = ko.observable(data.UserInfo.State);
    this.StateOptions = ko.observableArray(data.StateList);

    // Submit, Next button
    this.InvalidateForm = ko.observable(false);
    this.SubmitForm = function () {
        if (viewModel.errors().length == 0) {
            $('form').submit();
        }
        else {
            viewModel.errors.showAllMessages();
            this.InvalidateForm(true);
        }
    }
};

viewModel.ConfirmPassword = ko.observable().extend({
	validation: { validator: mustEqual, message: 'Passwords do not match.', params: viewModel.Password }
}),
viewModel.errors = ko.validation.group(viewModel);

// Third: Apply view model to view to handle action when user input data
ko.validation.rules.pattern.message = 'Invalid.';
ko.applyBindings(viewModel, document.getElementById("main"));